import React, { useState, useEffect } from 'react'
import { Table, Tag, Popconfirm, Card, Form, Input, Select, Button, message, Modal, Drawer } from 'antd'
import { EditOutlined, DeleteOutlined, SearchOutlined, SyncOutlined } from '@ant-design/icons'
import '../../DepartmentManage/views/style.css'
import TableToolbar from '../../../components/TableSetting/TableToolbar'
import { Store } from 'rc-field-form/lib/interface'
import { fetchRequest } from '../../../utils/Request'
import { url } from '../../../utils/url'
import { useRequest, useUnmount } from '@umijs/hooks'
import { useDispatch, useSelector } from 'react-redux'
import staffType from '../staffTypes'
import PersonInfo from './PersonInfo'
import AddUser from './AddUser'
import { actionTypes } from '../../DepartmentManage/actionTypes'
import ModifyUser from './ModifyUser'


interface RequestParams {
    "begin": number,
    "name": string,
    "phone": string
}

interface DetailInfo {
    visible: boolean,
    content: any
}

export default function PersonManageTable() {

    const columns = [{ title: "姓名", dataIndex: 'userName', key: 'userName' },
    { title: "联系电话", dataIndex: 'phone', key: 'phone' },
    {
        title: "管理部门", dataIndex: 'deptRelList', key: 'deptRelList',
        render: (record: any) => <Tag color="#f50">{record.length + "个"}</Tag>
    },
    {
        title: "角色", dataIndex: 'roleList', key: 'roleList',
        render: (record: any) => <Tag color="#f50">{record.length + "个"}</Tag>
    }, {
        title: "权限", dataIndex: 'authList', key: 'authList',
        render: (record: any) => <Tag color="#f50">{record.length + "个"}</Tag>
    },
    { title: "创建时间", dataIndex: 'createDate', key: 'createDate' },
    { title: "人员状态", dataIndex: 'state', key: 'state', render: (text: string) => <Tag color={text === "有效" ? "green" : "red"}>{text}</Tag> },
    {
        title: "操作", render: (record: any) => {
            return <small onClick={e => e.stopPropagation()}>
                <Tag className="tags-hover" color="#108ee9" icon={<EditOutlined />} onClick={() => setmodifyVisible({ visible: true, content: record })}>编辑</Tag>
                <Popconfirm title="确定要删除？" onConfirm={e => {
                    deleteUser.run({ userID: record.userID })
                    //TODO 后需要进行删除操作
                }}>
                    <Tag className="tags-hover delete" color="#f50" icon={<DeleteOutlined />}>删除</Tag>
                </Popconfirm>
            </small>
        }
    }]

    const [columnsKey, setcolumnsKey] = useState<any[]>([])

    const [realColumns, setrealColumns] = useState<any[]>([])

    const [detail, setdetail] = useState<DetailInfo>({ visible: false, content: null })

    const [addVisible, setaddVisible] = useState(false)

    const [modifyVisible, setmodifyVisible] = useState<DetailInfo>({ visible: false, content: null })


    // function handleModify(value:any)

    //点击刷新按钮
    function onRefresh() {
        // getDept.run()
        getStaffTable.refresh()
    }

    //点击新增按钮
    function onAdd() {
        // setaddVisible({ visible: true, deptID: undefined })
        setaddVisible(true)
    }

    function onColumnsChange(checkedList: any[]) {
        // console.log(checkedList)
        setcolumnsKey(checkedList)
    }

    //监听变化
    useEffect(() => {
        const realColumns = columns.filter(item => columnsKey.indexOf(item.key) !== -1)
        setrealColumns(realColumns)
    }, [columnsKey])

    const [form] = Form.useForm()


    function handleFinish(value: Store) {
        // console.log(value)
        const param = {
            name: typeof value.name === "undefined" ? "" : value.name,
            phone: typeof value.phone === "undefined" ? "" : value.phone
        }
        dispatch({ type: staffType.SET_STAFF_TABLE_PARAMS, payload: param })
    }

    function handleReset() {
        form.resetFields()
        const param = {
            name: "",
            phone: "",
            begin: 0
        }
        dispatch({ type: staffType.SET_STAFF_TABLE_PARAMS, payload: param })
    }


    //查询框
    const searchForm = (<Card className="search-form" > <Form form={form} layout="inline" onFinish={handleFinish} onReset={handleReset}>

        <Form.Item className="form-control-item" name="name" label="人员名称">
            <Input className="search-form-item" />
        </Form.Item>

        <Form.Item className="form-control-item" name="phone" label="人员电话">
            <Input className="search-form-item" />
        </Form.Item>


        <Form.Item className="form-control-item"  >
            <Button key="1" type="primary" icon={<SearchOutlined />} htmlType="submit" style={{ marginRight: '8px' }}>搜索</Button>
            <Button key="2" icon={<SyncOutlined />} htmlType="reset">重置</Button>

        </Form.Item>

    </Form>
    </Card>)


    const getStaffTable = useRequest(getStaffTableRequest, {
        manual: true,
        loadingDelay: 200
    })


    const deleteUser = useRequest(deleteUserRequest, {
        manual: true,
        loadingDelay: 200
    })

    //删除请求
    async function deleteUserRequest(params: any) {
        try {
            const json = await fetchRequest(url.DELETE_USER_URL, params);
            if (json.success) {
                message.destroy();
                message.success("删除成功!");
                if (tableData.staffTable.count > 10 && tableData.staffTable.count - 1 === tableData.requestParams.begin) {
                    dispatch({ type: staffType.SET_STAFF_TABLE_PARAMS, payload: { begin: tableData.requestParams.begin - 10 } })
                } else {
                    getStaffTable.run(tableData.requestParams)
                }
            } else {
                message.destroy();
                message.error(json.error)
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message)
        }
    }

    //异步请求获取信息
    async function getStaffTableRequest(params: RequestParams) {
        try {
            const json = await fetchRequest(url.GET_PERSON_MANAGE_TABLE, params);
            if (json.success) {
                dispatch({ type: staffType.GET_STAFF_PERSON_TABLE, payload: { data: json.data, count: json.count } })
            } else {
                message.destroy();
                message.error(json.error)
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message)
        }
    }

    const dispatch = useDispatch();
    const tableData = useSelector((state: any) => {
        return state.staffManage
    })


    // console.log(tableData)
    useEffect(() => {
        getStaffTable.run(tableData.requestParams)
    }, [tableData.requestParams])

    useUnmount(() => {
        dispatch({
            type: staffType.SET_STAFF_TABLE_PARAMS, payload: {
                phone: "",
                name: "",
                begin: 0
            }
        })
    })

    //当行点击的时候
    function onRowClick(record: any) {
        setdetail({ visible: true, content: record })
    }

    async function getDeptListRequest() {
        try {
            const json = await fetchRequest(url.GET_ALL_DEPT, "");
            //console.log('json:',json)
            if (json.success) {
                deleteEmpty(json.deptData)
                dispatch({ type: actionTypes.GET_DEPT_TABLE, payload: json.deptData })
            } else {
                message.destroy();
                message.error(json.error)
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message)
        }
    }


    //递归删除空的children
    function deleteEmpty(arr: any[]) {
        arr.map(item => {
            if (item.children.length === 0) {
                delete item.children
            } else {
                deleteEmpty(item.children)
            }
        })
    }

    const getDept = useRequest(getDeptListRequest, {
        loadingDelay: 200
    })

    //获取角色的信息
    async function getRoleRequest() {
        try {
            const json = await fetchRequest(url.GET_ROLE_LIST_URL, "");
            if (json.success) {
                dispatch({ type: staffType.GET_ROLE_LIST, payload: json.data })
            } else {
                message.destroy();
                message.error(json.error);
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message)
        }
    }

    const getRoleList = useRequest(getRoleRequest, {
        loadingDelay: 200
    })

    //当新增成功的时候
    function onAddsuccess() {
        setaddVisible(false);
        getStaffTable.run(tableData.requestParams)
    }

    //当修改成功的时候
    function onModifySuccess() {
        setmodifyVisible({ visible: false, content: modifyVisible.content });
        getStaffTable.run(tableData.requestParams)
    }


    //当翻页改变的时候
    function handlePageChange(value: number) {
        dispatch({ type: staffType.SET_STAFF_TABLE_PARAMS, payload: { begin: (value - 1) * 10 } })
    }

    return (
        <div>
            {searchForm}
            <Card className="search-form-table">
                <TableToolbar tableName="工号管理表" columns={columns} onColumnsChange={onColumnsChange} onRefresh={onRefresh} onAdd={onAdd} />
                <Table
                    pagination={{ hideOnSinglePage: true, simple: true, onChange: handlePageChange, total: tableData.staffTable.count, current: tableData.requestParams.begin / 10 + 1, showSizeChanger: false }}
                    rowKey={(record: any) => record.userID}
                    onRow={(record: any) => {
                        return { onClick: e => onRowClick(record) }
                    }} loading={getStaffTable.loading} columns={realColumns} dataSource={tableData.staffTable.data} />
            </Card>

            <Modal
                width="700px"
                destroyOnClose
                visible={detail.visible}
                title="人员信息"
                footer={null}
                centered
                onCancel={() => setdetail({ ...detail, visible: false })}>
                <PersonInfo content={detail.content} />
            </Modal>

            <Drawer
                width="700px"
                visible={addVisible}
                title="新增人员"
                destroyOnClose
                onClose={() => setaddVisible(false)}>
                <AddUser onAddSuccess={onAddsuccess} />
            </Drawer>


            <Drawer width="700px" visible={modifyVisible.visible} title="修改信息" destroyOnClose onClose={() => setmodifyVisible({ content: modifyVisible.content, visible: false })}>
                <ModifyUser content={modifyVisible.content} onModifySuccess={onModifySuccess} />
            </Drawer>


        </div>
    )
}
